package com.bizihang.security.browser.controller;

import com.bizihang.security.core.properties.SecurityConstants;
import com.bizihang.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.EnumMap;
import java.util.Map;
import java.util.Objects;

/**
 * 未授权跳转处理逻辑（需要登陆的的时候处理的逻辑）
 *
 * @author 毕子航 951755883@qq.com
 * @date 2018/08/15
 */
@Slf4j
@RestController
public class BrowserSecurityController {
	private static final String PREFIX_HTML = ".html";

	@Autowired
	SecurityProperties securityProperties;

	enum Result {
		success, code, body
	}

	private RequestCache requestCache = new HttpSessionRequestCache();

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	@RequestMapping(SecurityConstants.UNAUTHORIZED_REDIRECT_URL)
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public ResponseEntity a(HttpServletRequest request, HttpServletResponse response) {

		SavedRequest req = requestCache.getRequest(request, response);

		if (Objects.nonNull(req)) {
			String redirectUrl = req.getRedirectUrl();
			log.info("引发跳转的url:{}", redirectUrl);
			if (StringUtils.endsWithIgnoreCase(redirectUrl, PREFIX_HTML)) {
				try {
					redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		Map<Result, Object> resultMap = new EnumMap<>(Result.class);
		resultMap.put(Result.success, HttpStatus.UNAUTHORIZED.is2xxSuccessful());
		resultMap.put(Result.code, HttpStatus.UNAUTHORIZED.value());
		resultMap.put(Result.body, "访问的服务需要身份认证，请引导用户到登陆页面");
		return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(resultMap);
	}
}
